﻿#include "HiUnSafeSmartHeapListImpl.h"

#include <algorithm>

static void OnRelease_Default(void* prt) {
	//delete prt;
}

HiUnSafeSmartHeapListImpl::HiUnSafeSmartHeapListImpl(): releaseFunc(OnRelease_Default) {
}


HiUnSafeSmartHeapListImpl::~HiUnSafeSmartHeapListImpl() {
	for (auto it = memoryPtrs.begin(); it != memoryPtrs.end(); ++it) {
		this->releaseFunc(it->first);
		delete it->second;
	}
	
	memoryPtrs.clear();
	memorys.clear();
}

void HiUnSafeSmartHeapListImpl::Init(int count, const HiUnSafeSmartHeapList::ALLOC_FUN& allocFun, const HiUnSafeSmartHeapList::RELEASE_FUN& releaseFun) {	
	this->memorySize = count;
	this->releaseFunc = releaseFun;
	for (int i = 0; i < count; i++) {
		void* prt = allocFun();
		HiIndex* indexObj = new HiIndex(i, false, prt);
		memorys[i] = indexObj;
		memoryPtrs[prt] = indexObj;
	}
}

void* HiUnSafeSmartHeapListImpl::CreateData() {
	auto it = std::find_if(memorys.begin(), memorys.end(), [&](const Itor& item){
		return !item.second->isUsing;
	});
	if (memorys.end() == it) {
		return nullptr;
	}
	it->second->isUsing = true;
	return it->second->data;
}

int HiUnSafeSmartHeapListImpl::WaterLevel() {
	return (int)count_if(memorys.begin(), memorys.end(), [&](const Itor& item){
		return item.second->isUsing;
	});
}

void HiUnSafeSmartHeapListImpl::Destory(void* t) {
	auto it = memoryPtrs.find(t);
	if (memoryPtrs.end() == it) {
		return;
	}
	
	it->second->isUsing = false;
}